/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Facade;

import entity.Account;
import entity.Customer;
import exceptions.AccessDeniedException;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Vojtisek
 */
@Stateless
@RolesAllowed("customer")
public class AccountFacade implements AccountFacadeLocal {

    @PersistenceContext
    private EntityManager em;
    @Resource
    private SessionContext ctx;

    public Account getAccount(Integer accountId) throws AccessDeniedException, Exception {
        Customer c = getCurrentCustomer();
        Account ac = em.find(Account.class, accountId);
        if (!c.getAccounts().contains(ac)) {
            throw new AccessDeniedException();
        }
        return ac;
    }

    public Collection<Account> getAccounts() throws Exception {
        Customer cust = getCurrentCustomer();
        return cust.getAccounts();
    }

    public void createAccount(Account account) throws NullPointerException, Exception {
        Customer cust = getCurrentCustomer();
        account.setBalance(BigDecimal.valueOf(1000));
        account.setOwner(cust);
        cust.getAccounts().add(account);
        em.persist(account);
    }

    private Customer getCurrentCustomer() {
        String login = ctx.getCallerPrincipal().getName();
        Query query = em.createQuery("select c from Customer c where c.login=:login");
        query.setParameter("login", login);
        Customer cust = (Customer) query.getSingleResult();
        return cust;
    }

    public Account find(Object id) throws Exception {
        return em.find(Account.class, id);
    }
}
